package com.ruoyi.report.service.impl;

import com.deepoove.poi.data.PictureRenderData;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExportWordUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.jacob.Word2Pdf;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.equ.domain.EquBasic;
import com.ruoyi.equ.service.IEquBasicService;
import com.ruoyi.onlyoffice.domain.OnFile;
import com.ruoyi.onlyoffice.service.IOnFileService;
import com.ruoyi.report.domain.ReportInformation;
import com.ruoyi.report.domain.ReportOrginalimage;
import com.ruoyi.report.domain.entity.KyBaseTemplateEntity;
import com.ruoyi.report.domain.report.ReportBasic;
import com.ruoyi.report.domain.report.ReportItem;
import com.ruoyi.report.domain.report.ReportParam;
import com.ruoyi.report.domain.temp.ZixiecheTaskRespDTO;
import com.ruoyi.report.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;

/**
 * 数据导入报告SService业务层处理
 * 
 * @author luguanqing
 * @date 2020-11-30
 */
@Service
public class DataImportReportServiceImpl implements IDataImportReportService
{
    @Autowired
    private IReportBasicService reportBasicService;

    @Autowired
    private IReportItemService reportItemService;

    @Autowired
    private IReportParamService reportParamService;

    @Autowired
    private IReportInformationService reportInformationService;

    @Autowired
    private IEquBasicService equBasicService;

    @Autowired
    private IKyBaseTemplateService kyBaseTemplateService;

    @Autowired
    private IOnFileService onFileService;

    @Autowired
    private IReportOrginalimageService reportOrginalimageService;

    /**
     * 保存自卸车数据
     * @param zixiecheTaskRespDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveZixiecheData(ZixiecheTaskRespDTO zixiecheTaskRespDTO) {
        //获取基本信息数据
        ReportBasic reportBasic = zixiecheTaskRespDTO.getBasic();
        int res = 0;
        //数据基本保存
        if(null != reportBasic) {
            res =  reportBasicService.insertReportBasic(reportBasic);
            //基本数据保存成功后生成报告数据
            if(res > 0) {
                //报告信息保存
                ReportInformation reportInformation = new ReportInformation();
                String reportId = IdUtils.fastUUID();
                reportInformation.setId(reportId);
                reportInformation.setReportNum(reportBasic.getReportNum());
                reportInformation.setClient(reportBasic.getCompanyName());
                reportInformation.setReportType(reportBasic.getEquName());
                reportInformation.setSampleType(reportBasic.getEquName());
                reportInformation.setAgreementNum(reportBasic.getContractNo());
                reportInformation.setTestMethod("1");
                reportInformation.setTestDate(reportBasic.getInspectionDate());
                reportInformation.setNextTestDate(reportBasic.getNextInspectionDate());
                reportInformation.setTestPlace(reportBasic.getInspectionPlace());
                reportInformation.setState("0");
                reportInformation.setUploadType("2");
                reportInformation.setUploader(SecurityUtils.getLoginUser().getUser().getNickName());
                reportInformation.setTester(reportBasic.getSubTester());
                reportInformation.setChiefInspector(SecurityUtils.getLoginUser().getUser().getNickName());
                reportInformation.setChiefTime(DateUtils.getNowDate());
                reportInformationService.insertReportInformation(reportInformation);
                //附件图片关联现场照片
                if(StringUtils.isNotEmpty(reportBasic.getAttachmentPaths())) {
                    String[] attachmentPaths = reportBasic.getAttachmentPaths().split(",");
                    for(String attachmentPath : attachmentPaths) {
                        ReportOrginalimage reportOrginalimage = new ReportOrginalimage();
                        reportOrginalimage.setId(IdUtils.fastUUID());
                        reportOrginalimage.setoId(reportId);
                        reportOrginalimage.setProfile(attachmentPath);
                        reportOrginalimageService.insertReportOrginalimage(reportOrginalimage);
                        }
                    }
                }
            }
            //保存检测项目数据
            List<ReportItem> reportItems = zixiecheTaskRespDTO.getItems();
            if(reportItems != null && reportItems.size() > 0) {
                reportItems.forEach(item -> {
                    item.setReportNum(reportBasic.getReportNum());
                });
                reportItemService.insertReportItems(reportItems);
            }
            //保存检测参数数据
            List<ReportParam> reportParams = zixiecheTaskRespDTO.getParams();
            if(reportParams != null && reportParams.size() > 0) {
                reportParams.forEach(param -> {
                    param.setReportNum(reportBasic.getReportNum());
                });
                reportParamService.insertReportParams(reportParams);
            }
        return res;
    }

    /**
     * 修改自卸车数据
     * @param zixiecheTaskRespDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateZixiecheData(ZixiecheTaskRespDTO zixiecheTaskRespDTO) {
        //删除原有数据
        int ret = deleteReportDataByReportNum(zixiecheTaskRespDTO.getBasic().getReportNum());
        int res = 0;
        if(ret > 0) {
            //保存新数据
            res = saveZixiecheData(zixiecheTaskRespDTO);
        }
        return res;
    }

    /**
     * 根据报告编号删除数据
     * @param reportNum
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteReportDataByReportNum(String reportNum) {
        //获取报告id
        ReportInformation reportInformation = reportInformationService.selectReportInformationByNum(reportNum);
        //删除基本数据信息
        int ret =  reportBasicService.deleteReportBasicByReportNum(reportNum);
        if(ret > 0) {
            //删除报告信息
             reportInformationService.deleteReportInformationByReportNum(reportNum);
             //删除检测项数据
             reportItemService.deleteReportItemByReportNum(reportNum);
             //删除检测参数数据
             reportParamService.deleteReportParamByReportNum(reportNum);
             //删除原始记录图片
            reportOrginalimageService.deleteReportOrginalimageByOid(reportInformation.getId());
        }
        return ret;
    }

    /**
     * 根据报告编号查询数据
     * @param reportNum
     * @return
     */
    @Override
    public ZixiecheTaskRespDTO getReportDataByReportNum(String reportNum) {
        ZixiecheTaskRespDTO zixiecheTaskRespDTO = new ZixiecheTaskRespDTO();
        //根据报告编号获取基本信息
        ReportBasic reportBasic = reportBasicService.selectReportBasicByReportNum(reportNum);
        //获取设备信息
        if(null != reportBasic && null != reportBasic.getEquGroup()) {
            //根据设备组和标签获取设备列表信息
            EquBasic equBasic = new EquBasic();
            equBasic.setLabels(reportBasic.getEquName());
            equBasic.setEquGroups(reportBasic.getEquGroup());
            List<EquBasic> equBasics = equBasicService.selectEquBasicList(equBasic);
            if(null != equBasics && equBasics.size() > 0) {
                zixiecheTaskRespDTO.setEquipment(equBasics);
            }
        }
        //根据报告编号获取检测项目
        List<ReportItem> reportItems = reportItemService.selectReportItemByReportNum(reportNum);
        //根据报告编号获取检测参数
        List<ReportParam> reportParams = reportParamService.selectReportParamByReportNum(reportNum);
        zixiecheTaskRespDTO.setBasic(reportBasic);
        zixiecheTaskRespDTO.setItems(reportItems);
        zixiecheTaskRespDTO.setParams(reportParams);
        return zixiecheTaskRespDTO;
    }

    /**
     * 生成自卸车报告
     * @param reportNum
     * @return
     */
    @Override
    public String generateZixiecheReport(String reportNum) {
        //获取报告数据
        ZixiecheTaskRespDTO zixiecheTaskRespDTO = getReportDataByReportNum(reportNum);
        //获取报告信息
        ReportInformation reportInformation = reportInformationService.selectReportInformationByNum(reportNum);
        //生成报告
        if(null != zixiecheTaskRespDTO) {
            //获取报告基本信息
            ReportBasic reportBasic = zixiecheTaskRespDTO.getBasic();
            //获取报告检测项目
            List<ReportItem> reportItems = zixiecheTaskRespDTO.getItems();
            //获取报告检测参数
            List<ReportParam> reportParams = zixiecheTaskRespDTO.getParams();
            //获取设备信息
            List<EquBasic> equipment = zixiecheTaskRespDTO.getEquipment();
            //获取报告模板
            KyBaseTemplateEntity kyBaseTemplateEntity = kyBaseTemplateService.selectKyBaseTemplateByTempName(reportBasic.getEquName());
            //导入报告中
            Map<String, Object> params = new HashMap<>();
            //基本检测信息
            if(null != reportBasic) {
                params.put("报告编号", reportBasic.getReportNum());
                params.put("委托单位", reportBasic.getCompanyName());
                params.put("受检单位", reportBasic.getInspectedUnit());
                params.put("检验日期", DateUtils.formatDate(reportBasic.getInspectionDate(), DateUtils.CYYYY_MM_DD));
                params.put("下次检验日期", DateUtils.formatDate(reportBasic.getNextInspectionDate(), DateUtils.CYYYY_MM_DD));
                params.put("受检单位地址", reportBasic.getInspectedAddress());
                params.put("设备状态", reportBasic.getDeviceStatus());
                params.put("合同编号", reportBasic.getContractNo());
                params.put("检验地点", reportBasic.getInspectionPlace());
                params.put("温度", reportBasic.getTemperature());
                params.put("湿度", reportBasic.getHumidity());
                params.put("大气压", reportBasic.getAtmosphericPressure());
            }
            //设备参数信息
            List<Map<String, Object>> equList = new ArrayList<>();
            if(null != equipment && equipment.size() > 0) {
                for(int i = 0 ; i < equipment.size(); i++) {
                    Map<String, Object> equMap = new HashMap<>();
                    equMap.put("名称", equipment.get(i).getEquName());
                    equMap.put("管理编号", equipment.get(i).getEquNum());
                    equMap.put("规格型号", equipment.get(i).getEquModel());
                    //格式化处理准确度数据，从富文本变成word格式
                    String equUncertainty = equipment.get(i).getEquUncertainty();
                    if(StringUtils.isNotBlank(equUncertainty)) {
                        equUncertainty = StringUtils.replace(equUncertainty, "<p>", "");
                        equUncertainty = StringUtils.replace(equUncertainty, "</p>", "");
                        equUncertainty = StringUtils.replace(equUncertainty, "&nbsp;", "");
                        equUncertainty = StringUtils.replace(equUncertainty, "&nbsp;", "");
                    }
                    equMap.put("准确度", equUncertainty);
                    equMap.put("检定/校准证书编号", equipment.get(i).getEquCertificate());
                    equMap.put("有效期至", DateUtils.formatDate(equipment.get(i).getEquInvalidity(), DateUtils.YYYY_MM_DD));
                    equList.add(equMap);
                }
            }
            //受检设备参数信息
            if(null != reportParams && reportParams.size() > 0) {
                for(int i = 0 ; i < reportParams.size(); i++) {
                    //格式化去除()中的内容标签
                    String paramName = reportParams.get(i).getParamName().replaceAll("\\(.*?\\)", "");
                    params.put(paramName, reportParams.get(i).getValue());
                }
            }
            //检测项目信息
            if(null != reportItems && reportItems.size() > 0) {
                for(int i = 0 ; i < reportItems.size(); i++) {
                    params.put("判定" + (i + 1), reportItems.get(i).getJudgment());
                    params.put("结果" + (i + 1), reportItems.get(i).getVariableValue() != null ? reportItems.get(i).getVariableValue() : reportItems.get(i).getResult());
                }
            }
            //附件图
            String[] imgs =  reportBasic.getAttachmentPaths().split(",");
            for(int i = 0 ; i < imgs.length; i++) {
                params.put("附件图" + (i + 1),  new PictureRenderData(600, 400, StringUtils.replace(imgs[i], "/profile", RuoYiConfig.getProfile())));
            }
            //判断是否已审批通过且存在签名
            int picW = 66;
            int picH = 33;
            String imgPath = RuoYiConfig.getSign();
            //签字内容
            if(StringUtils.isNotEmpty(reportInformation.getChiefInspector())) {
                //主检
                params.put("检验", new PictureRenderData(picW, picH, StringUtils.replace("/profile/sign/" + reportInformation.getChiefInspector() + ".png", "/profile/sign", imgPath)));
//                params.put("主检日期", reportInformation.getChiefTime() != null ? DateUtils.formatDate(reportInformation.getChiefTime(), DateUtils.CYYYY_MM_DD) : "");
//                params.put("主检签名", new PictureRenderData(picW, picH, StringUtils.replace("/profile/sign/" + reportInformation.getChiefInspector() + ".png", "/profile/sign", imgPath)));
            }
            if(StringUtils.isNotEmpty(reportInformation.getExamInspector())) {
                //审核
                params.put("审核", new PictureRenderData(picW, picH, StringUtils.replace("/profile/sign/" + reportInformation.getExamInspector() + ".png", "/profile/sign", imgPath)));
//                params.put("审核日期", reportInformation.getExamTime() != null ? DateUtils.formatDate(reportInformation.getExamTime(), DateUtils.CYYYY_MM_DD) : "");
//                params.put("审核签名", new PictureRenderData(picW, picH, StringUtils.replace("/profile/sign/" + reportInformation.getExamInspector() + ".png", "/profile/sign", imgPath)));
            }
            if(StringUtils.isNotEmpty(reportInformation.getApprInspector())) {
                params.put("批准", new PictureRenderData(picW, picH, StringUtils.replace("/profile/sign/" + reportInformation.getApprInspector() + ".png", "/profile/sign", imgPath)));
//                params.put("批准日期", reportInformation.getApprTime() != null ? DateUtils.formatDate(reportInformation.getApprTime(), DateUtils.CYYYY_MM_DD) : "");
//                params.put("批准签名", new PictureRenderData(picW, picH, StringUtils.replace("/profile/sign/" + reportInformation.getApprInspector() + ".png", "/profile/sign", imgPath)));
            }
            //list结果传到map
            params.put("设备数据List", equList);
            //保存文件路径
            String docRootPath = RuoYiConfig.getProfile() + RuoYiConfig.getDocumentPath() + "/";
            //文件名
            String docFileName = System.currentTimeMillis() + "-zxch.docx";
            //生成报告
            boolean isOk = ExportWordUtils.exportWord(RuoYiConfig.getProfile() + RuoYiConfig.getTemplatePath() + "/" + kyBaseTemplateEntity.getTempName(), docRootPath, docFileName, params);
            System.out.println("isOK: 生成测试报告" + isOk + " docFileName: " + docFileName);
            if(isOk) {
                return "/profile/document/" + docFileName;
            }else {
                return "";
            }
        }
        return "";
    }

    /**
     * 根据word文件路径生成pdf文件
     */
    public String generatePdfFile(String wordFilePath){
        //获取报告路径
        String profile = RuoYiConfig.getProfile();
        //获取报告地址
        wordFilePath = StringUtils.replace(wordFilePath, "/profile", profile);
        String pdfPath = StringUtils.substring(wordFilePath, 0, wordFilePath.lastIndexOf(".")) + ".pdf";
        Word2Pdf word2Pdf = new Word2Pdf();
        word2Pdf.word2pdfUtil(wordFilePath, pdfPath);
         pdfPath = StringUtils.replace(pdfPath, profile, "/profile");
         return pdfPath;
    }

    /**
     * 生成报告并保存送审
     * @param reportNum
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveReport(String reportNum) throws IOException {
        //获取生成word报告的url路径
        String url = generateZixiecheReport(reportNum);
        if(null != url) {
            //更新报告基本信息并导入onlyoffice中
            ReportInformation reportInformation = new ReportInformation();
            String id = IdUtils.fastSimpleUUID();
            reportInformation.setReportNum(reportNum);
            reportInformation.setReportUrl(url);
            reportInformation.setState("1");
            reportInformation.setFileId(id);
            int ret = reportInformationService.updateReportInformationByReportNum(reportInformation);
            //上传到onlyoffice服务器
            if(ret > 0 && StringUtils.isNotEmpty(reportInformation.getReportUrl())) {
                //保存成功后添加记录到历史oo列表中
                OnFile onFile = new OnFile();
                onFile.setFileId(id);
                String reportUrl = reportInformation.getReportUrl();
                onFile.setFileName(reportInformation.getReportNum() + StringUtils.substring(reportUrl, reportUrl.indexOf(".")));
                onFile.setFileType(StringUtils.substring(reportUrl, reportUrl.indexOf(".") + 1));
                onFile.setVersion("1.0.0");
                onFile.setCreatedTimes(DateUtils.formatDate(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS));
                onFile.setUserId(String.valueOf(SecurityUtils.getLoginUser().getUser().getUserId()));
                onFile.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());
                onFile.setReportId(reportInformationService.selectReportInformationByNum(reportNum).getId());
                onFileService.insertOnFile(onFile);
                //将当前文件保存到onlyoffice服务器地址下
                FileUtils fileUtils = new FileUtils();
                fileUtils.copyFile(StringUtils.replace(reportUrl, "/profile", RuoYiConfig.getProfile()), RuoYiConfig.getOoFile() +"\\"+onFile.getFileId()+"."+onFile.getFileType());
            }
            return  ret;
        }
        return 0;
    }
}
